﻿namespace BEGDC.CC.Web.EZVisit.Controls
{
    #region Using Directives

    using System;
    using System.Data;
    using System.Linq;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using ASBCC.Database.Entity;
    using ASBCC.Database.Service;
    using Utility.Extensions;

    #endregion

    public partial class EZVRequestAttachment : EZVRequestBaseControl
    {
        protected override void PreRenderPartialView()
        {
            this.SetVisibility();
            this.SetViewData();
        }

        protected override void SetViewData()
        {
            if (this.EZVisitApplication == null)
            {
                return;
            }

            this.lbAppNo.Text = this.EZVisitApplication.AppNo;
            this.BindAttachments();
        }

        protected override void SetVisibility()
        {
            base.SetVisibility();

            this.dgAttachment.Columns[7].Visible = this.Editable;
        }

        protected override bool Validate(out string error)
        {
            error = string.Empty;

            if (this.CurrentActionType.IsNotNullOrWhiteSpace())
            {
                if (this.EZVisitApplication != null && this.EZVisitApplication.IsInSalesContract.GetValueOrDefault(true))
                {
                    if (this.edt_Upload1.Visible)
                    {
                        error = @"- [Application Attch.] Contract Information attachment was not provided.\n";
                    }

                    if (this.edt_Upload2.Visible)
                    {
                        error += @"- [Application Attch.] Contract Execution Letter attachment was not provided.\n";
                    }
                }

                if (this.edt_Upload3.Visible)
                {
                    error += @"- [Application Attch.] Agenda attachment was not provided.\n";
                }

                if (this.edt_Upload4.Visible)
                {
                    error += @"- [Application Attch.] Expense attachment was not provided.\n";
                }

                if (this.edt_Upload5.Visible)
                {
                    error += @"- [Application Attch.] TA Quotation attachment was not provided.\n";
                }

                if (this.edt_Upload6.Visible)
                {
                    error += @"- [Application Attch.] Host Confirmation attachment was not provided.\n";
                }
            }

            return error.Length == 0;
        }

        public void BindAttachments()
        {
            if (this.EZVisitApplication == null || this.EZVisitApplication.AppIDIsNull() || !this.Visible)
            {
                return;
            }

            var dt = this.GetAttachments().OfType<UploadFileTableEntity>().ToDataTable();

            var dv = dt.DefaultView;

            if (this.EZVisitApplication.QuotationType.IsNotNullOrWhiteSpace())
            {
                dv.RowFilter = string.Format("AttachmentTypeKey<>'{0}'", this.EZVisitApplication.QuotationType);
            }

            this.dgAttachment.DataSource = dv.ToTable();
            this.dgAttachment.DataBind();

            if (!this.Editable)
            {
                return;
            }

            this.edt_Upload1.Visible = true;
            this.edt_Upload2.Visible = true;
            this.edt_Upload3.Visible = true;
            this.edt_Upload4.Visible = true;
            this.edt_Upload5.Visible = true;
            this.edt_Upload6.Visible = true;
            this.edt_Upload7.Visible = true;

            foreach (DataRow row in dt.Rows)
            {
                switch (row["AttachmentTypeKey"].ToString().ToLowerInvariant())
                {
                    case "contract":
                        this.edt_Upload1.Visible = false;
                        break;
                    case "contractexecutionletter":
                        this.edt_Upload2.Visible = false;
                        break;
                    case "agenda":
                        this.edt_Upload3.Visible = false;
                        break;
                    case "budget":
                        this.edt_Upload4.Visible = false;
                        break;
                    case "taquotation":
                        this.edt_Upload5.Visible = false;
                        break;
                    case "hostconfirmation":
                        this.edt_Upload6.Visible = false;
                        break;
                    case "others":
                        this.edt_Upload7.Visible = false;
                        break;
                }
            }
        }

        protected void dgAttachment_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if ((e.Item.ItemType != ListItemType.Item) && (e.Item.ItemType != ListItemType.AlternatingItem))
            {
                return;
            }

            var cell = e.Item.Cells[7];

            var btnDelete = (ImageButton) cell.FindControl("btnDelete");
            btnDelete.Attributes.Add("onclick", "return confirm('Are you sure to delete this item?');");
        }

        protected void dgAttachment_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
            DeleteAttachement(Convert.ToInt32(e.Item.Cells[0].Text));

            string attchType = e.Item.Cells[6].Text;

            if (attchType.IsNotNullOrWhiteSpace())
            {
                this.BindAttachments();

                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "reload" + attchType, "reload('" + attchType + "');", true);
            }
        }

        private UploadFileTableEntitySet GetAttachments()
        {
            string condition = string.Format("AppID={0} and IsEnabled=1 and AttachmentTypeKey not in ('HostPostTripConfirmationDomestic', 'HostPostTripConfirmationOversea', 'CustomerChanged', 'TASettlement', 'EZVisitReapprovalMail', 'AgendaChanged')", this.EZVisitApplication.AppID);

            return UploadFileManager.SelectByCondition(condition);
        }

        private static void DeleteAttachement(int fileId)
        {
            var attachment = UploadFileManager.SelectByKeys(fileId);

            if (attachment == null)
            {
                return;
            }

            attachment.IsEnabled = false;
            UploadFileManager.Update(attachment);
        }
    }
}